package com.example.librarymanagementsystem.Controller;

import com.example.librarymanagementsystem.constant.Constants;
import com.example.librarymanagementsystem.model.Result;
import com.example.librarymanagementsystem.model.UserInfo;
import com.example.librarymanagementsystem.severice.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService service;
    @RequestMapping(value = "/login",produces = "application/json")
    public Result login(String userName, String password, HttpSession session){
        if(!StringUtils.hasLength(userName)||!StringUtils.hasLength(password)){
            return Result.fail("用户名或者密码为空");
        }
        //用户名或者密码错误
        //由于还没有学习连接数据库，所以先暂时这么写
        //判断错误这么写能够减少if的嵌套,如果if实在太多使用方法进行嵌套
        UserInfo userInfo = service.getUserinfo(userName);
        if(userInfo == null){
            return Result.fail("用户不存在");
        }
        if(!password.equals(userInfo.getPassword())){
            return Result.fail("密码错误");
        }
        //根据用户名称，去数据库查询用户信息，如果未查询到，说明用户不存在
        //如果用户查询到的密码不一致说明密码错误
        //正确的情况
        session.setAttribute(Constants.USER_SESSION_KEY,userInfo);
        return Result.success("");
    }
}
